#coding: utf-8

# Copyright (c) P SOFTHOUSE. All rights reserved.

import maya.cmds as cmds
import maya.mel as mel
import json

from PencilLineGuiUtils import *

def showAuthorizeDialog():
    if False:
        #モーダルの場合
        def noresize_ui():
            fixDialogSize()
            authorizeDialogUi()
        cmds.layoutDialog(title=getLocalizedString("kNetworkAuthorizeTitle"), ui=noresize_ui)
    else:
        #モードレスの場合
        authwin = "pcl4AuthWindow"
        if cmds.window(authwin, exists=True):
            cmds.showWindow(authwin)
            return
        if cmds.windowPref(authwin, exists=True):
            cmds.windowPref(authwin, remove=True);
        cmds.window(authwin, title=getLocalizedString("kNetworkAuthorizeTitle"), sizeable=False, maximizeButton=False, minimizeButton=False)
        authorizeDialogUi()
        cmds.showWindow(authwin)

def authorizeDialogUi():
    top_layout = cmds.columnLayout(width=420, adjustableColumn=True)

    cmds.frameLayout(label=getLocalizedString("kNetworkAuthorizeStatusLabel")
                        #, collapsable=True, borderVisible=True
                        , marginHeight=10, marginWidth=10)
    cmds.columnLayout(adjustableColumn=True, rowSpacing=10)

    #製品シリアル
    cmds.rowLayout(numberOfColumns=2, adjustableColumn=2
                        , columnAttach=[(1, 'both', 0), (2, 'left', 10)]
                        )
    cmds.text(label=getLocalizedString("kNetworkAuthorizeSerialIDLabel"))
    serialField = cmds.textField(editable=False)

    #取得/返却
    cmds.setParent('..')
    cmds.rowLayout(numberOfColumns=3, adjustableColumn=1
                        , columnAttach=[(2, 'left', 10), (3, 'left', 10)]
                        )
    cmds.text(label='')
    requestButton = cmds.button(label=getLocalizedString("kNetworkAuthorizeRequestButton"), width=80)
    releaseButton = cmds.button(label=getLocalizedString("kNetworkAuthorizeReleaseButton"), width=80)

    #Netwok settings
    cmds.setParent(top_layout)
    cmds.rowLayout(numberOfColumns=1, adjustableColumn=1
                        , columnAttach=[(1, 'both', 100)]
                        , height=50
                        )
    settingsButton = cmds.button(label=getLocalizedString("kNetworkAuthorizeSettingsButton"))
    
    """
    on Load
    """
    authCheckResult = mel.eval("pcl4license -status")
    if(authCheckResult == "OK"):
        setButtonEnabled(requestButton, False)
        setButtonEnabled(releaseButton, True)
        licenseInfo = json.loads(mel.eval("pcl4license -info"))
        setText(serialField, licenseInfo["serialCode"])
    elif(authCheckResult == "Error_NoSettings"):
        setButtonEnabled(requestButton, False)
        setButtonEnabled(releaseButton, False)
        setText(serialField, getLocalizedString("kNetworkErrorSettingsNoExisits"))
    else:
        setButtonEnabled(requestButton, True)
        setButtonEnabled(releaseButton, False)
        setText(serialField, getLocalizedString("kNetworkErrorLicenseInvalid"))

    """
    Event
    """
    def onClickRequestButton():
        result = json.loads(mel.eval("pcl4license -request"))
        if result["status"] == "OK":
            licenseInfo = json.loads(mel.eval("pcl4license -info"))
            setText(serialField, licenseInfo["serialCode"])
            setButtonEnabled(requestButton, False)
            setButtonEnabled(releaseButton, True)
            
            # Refresh the attibute editor templates
            mel.eval('refreshEditorTemplates') # Command also exists as Python command, but it does not work!
            cmds.refresh()
        else:
            errorDialog(result)

    cmds.button(requestButton, edit=True, command=lambda *args: onClickRequestButton())

    def onClickReleaseButton():
        result = json.loads(mel.eval("pcl4license -release"))
        if result["status"] == "OK":
            setButtonEnabled(requestButton, True)
            setButtonEnabled(releaseButton, False)
            setText(serialField, getLocalizedString("kNetworkErrorLicenseInvalid"))
        else:
            errorDialog(result)

        # Refresh the attibute editor templates (regardless of success or failure)
        mel.eval('refreshEditorTemplates') # Command also exists as Python command, but it does not work!
        cmds.refresh()


    cmds.button(releaseButton, edit=True, command=lambda *args: onClickReleaseButton())

    def onClickSettingsButton():
        launchPencilTool("NLSetting", isModal=True)
        authCheckResult = mel.eval("pcl4license -status")
        if(authCheckResult == "Error"):
            if not cmds.button(requestButton, query=True, enable=True):
                setButtonEnabled(requestButton, True)
                setButtonEnabled(releaseButton, False)
                setText(serialField, getLocalizedString("kNetworkErrorLicenseInvalid"))


    cmds.button(settingsButton, edit=True, command=lambda *args: onClickSettingsButton())

    def errorDialog(param):
            cmds.confirmDialog(
                title=getLocalizedString("kNetworkErrorDialogTitle"),
                message=u"Error Code {}\n{}".format(param["code"], param["message"]),
                icon="warning",
                button="OK",
                defaultButton="OK")
